package sys

import (
	"errors"
	"gitee.com/freelifer/module-admin/model/request"
	"github.com/casbin/casbin/v2"
	gormadapter "github.com/casbin/gorm-adapter/v3"
	"github.com/go-spring/spring-core/gs"
	"gorm.io/gorm"
	"log"
)

func init() {
	// SpringBoot.RegisterBean(new(Service)).AsInterface((*types.FileProvider)(nil))
	gs.Object(new(CasbinService)).Init(func(c *CasbinService) {
		a, err := gormadapter.NewAdapterByDB(c.DB)
		if err != nil {
			log.Fatalf("gormadapter.NewAdapterByDB error %s\n " + err.Error())
		}
		syncedEnforcer, err := casbin.NewSyncedEnforcer("config/rbac_model.conf", a)
		if err != nil {
			log.Fatalf("casbin.NewSyncedEnforcer error %s\n " + err.Error())
		}
		err = syncedEnforcer.LoadPolicy()
		if err != nil {
			log.Fatalf("syncedEnforcer.LoadPolicy error %s\n " + err.Error())
		}
		c.Enforcer = syncedEnforcer
	})
}

type CasbinService struct {
	DB       *gorm.DB `autowire:""`
	Enforcer *casbin.SyncedEnforcer
}

func (casbinService *CasbinService) UpdateCasbin(roleId string, casbinInfos []request.CasbinInfo) error {
	casbinService.ClearCasbin(0, roleId)
	rules := [][]string{}
	for _, v := range casbinInfos {
		rules = append(rules, []string{roleId, v.Path, v.Method})
	}
	success, _ := casbinService.Enforcer.AddPolicies(rules)
	if !success {
		return errors.New("存在相同api,添加失败,请联系管理员")
	}
	return nil
}

func (casbinService *CasbinService) GetPolicyPathByRoleId(roleId string) (pathMaps []request.CasbinInfo) {
	list := casbinService.Enforcer.GetFilteredPolicy(0, roleId)

	for _, v := range list {
		pathMaps = append(pathMaps, request.CasbinInfo{
			Path:   v[1],
			Method: v[2],
		})
	}
	return pathMaps
}

// 清除匹配的权限
func (casbinService *CasbinService) ClearCasbin(v int, p ...string) bool {
	success, _ := casbinService.Enforcer.RemoveFilteredPolicy(v, p...)
	return success
}
